/* eslint-disable no-case-declarations */
/* eslint-disable no-debugger */
// import { isEmpty } from "@/utils/utils";
import { ProSchemaValueEnumType } from "@ant-design/pro-components";
import { Badge, Tag } from "antd";
import { DefaultOptionType } from "antd/es/select";
import { isEmpty } from "ut2";
import React from "react";

export interface DictValueEnumType extends ProSchemaValueEnumType {
	id?: string | number;
	key?: string | number;
	value: string | number;
	label: string;
	color?: string;
}

export interface DictOptionType extends DefaultOptionType {
	id?: string | number;
	key?: string | number;
	text: string;
	color?: string;
}

export type DictValueEnum = Record<string | number, DictValueEnumType>;

export type DictTagProps = {
	key?: string | number;
	value?: string | number;
	enums?: DictValueEnum;
	options?: DictOptionType[];
	type?: "tag" | "badge" | "normal" | undefined;
	defaultColor?: string;
	defaultValue?: string;
};

const DictTag: React.FC<DictTagProps> = props => {
	const { value, enums, options, defaultColor = "processing", defaultValue } = props;

	function getDictLabelByValue(value: string | number | undefined): string {
		if (isEmpty(value)) return defaultValue ? defaultValue : "";
		if (enums) {
			const item = enums[value];
			if (!item) {
				return defaultValue ? defaultValue : "";
			}
			return item?.label;
		}
		if (options) {
			if (!Array.isArray(options)) return "";
			for (const item of options) {
				if (item?.value === value) {
					return item?.text;
				}
			}
		}
		return String(value);
	}

	const getTagText = (): string => {
		return getDictLabelByValue(value);
	};

	const getTagColor = (value: any): string | undefined => {
		if (isEmpty(value)) return "";
		if (enums) {
			const item = enums[value];

			return item?.color ? String(item.color) : defaultColor;
		}
		if (options) {
			if (!Array.isArray(options)) return "";
			for (const item of options) {
				if (item.value === value) {
					return item?.color ? String(item?.color) : defaultColor;
				}
			}
		}
	};

	// 字典类型
	const swidthDict = (type: "tag" | "badge" | "normal" | undefined) => {
		switch (type) {
			case "tag":
				return <Tag color={getTagColor(value)}>{getTagText()}</Tag>;
			case "badge":
				let color = getTagColor(value);
				const colorType = color?.startsWith("#") ? "color" : "status";
				return (
					<>
						{/* @ts-ignore */}
						{colorType === "status" && <Badge status={color} text={getTagText()} />}
						{colorType === "color" && <Badge color={color} text={getTagText()} />}
					</>
				);
			case "normal":
				return <>{getTagText()}</>;
			default:
				return <>{getTagText()}</>;
		}
	};
	return <>{swidthDict(props.type)}</>;
};

export default DictTag;
